import IconDouyin from '@/components/icon/IconDouyin';
import IconKuaishou from '@/components/icon/IconKuaishou';
import { cascadersSource } from '@/services/api/api-monitor-source';
import type { ActionType, FormInstance, ProColumns } from '@ant-design/pro-components';
import {
    PageContainer,
    ProForm,
    ProFormCascader,
    ProFormDateRangePicker,
    ProFormRadio,
    ProTable,
    QueryFilter
} from '@ant-design/pro-components';
import { useAccess } from '@umijs/max';
import { Button, Cascader, Flex, Space, Tag } from 'antd';
import moment from 'moment';
import RcResizeObserver from 'rc-resize-observer';
import { useEffect, useRef, useState } from 'react';
import { Miscalculation, Pass, Return } from './ActionsMonitorLinkage';
import AddMonitorLinkage from './AddMonitorLinkage';
import DetailMonitorLinkage from './DetailMonitorLinkage';
import { mediaList, monitorLinkageUpdate, pageMonitorLinkage, platformList } from '@/services/api/api-monitor-linkage';
import { pageMonitorVideo, pageMonitorVideoRecordStatistics } from '@/services/api/api-monitor-video';
interface PageContainerMonitorLinkageProps { }

const PageContainerMonitorLinkage: React.FC<PageContainerMonitorLinkageProps> = (props) => {

    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();


    const [cascadersSourceData, setCascadersSourceDataState] = useState<
        MonitorData.CascadersSource[]
    >([]);

    const [pageMonitorVideoRecordStatisticsData, setPageMonitorVideoRecordStatisticsDataState] =
        useState<MonitorVideoData.VideoRecordPageStatistics[]>([]);

    const [optionsCascadersSourceData, setOptionsCascadersSourceDataState] = useState<
        MonitorData.CascadersSource[]
    >([]);

    const [optionsPlatformData, setOptionsPlatformData] = useState()

    /**
    * 搜索参数
    */
    const [queryParam, setQueryParamState] = useState({});

    const handleResolve = async (id: string) => {
        const res = await monitorLinkageUpdate({ id })
        console.log(res);
    }


    const columns: ProColumns<MonitorVideoData.VideoRecordPage>[] = [
        {
            title: '标题',
            dataIndex: 'content',
            width: '650px',
            hideInSearch: true,
            ellipsis: true,
            render: (dom, row) => (
                <DetailMonitorLinkage
                    data={row}
                    onRefurbish={() => {
                        actionRef.current?.reload()
                    }}
                />
            ),
        },
        {
            title: '账号',
            key: 'source',
            dataIndex: 'sourceName',
            width: 230,
            render: (dom, row) => (
                <Flex align="center" justify="left" gap="small">
                    {row.sourceChannelName == '抖音' ? (
                        <IconDouyin width={20} height={20} />
                    ) : (
                        <IconKuaishou width={20} height={20} />
                    )}
                    {row.sourceName}
                </Flex>
            ),
        },
        {
            title: '发布时间',
            dataIndex: 'releaseTime',
            key: 'dates',
            width: '180px',
            align: 'center',
            search: false,
        },
        {
            title: '操作',
            dataIndex: 'articleUrl',
            key: 'articleUrl',
            width: '120px',
            align: 'center',
            search: false,
            render: (dom, entity, index, action, schema) => (
                <a onClick={() => handleResolve(entity?.id)}>处理</a>
            ),
        },
    ];
    // const columns: ProColumns<DatahubRecordData.PretreatmentRecordPage>[] = [
    //     {
    //         title: '状态',
    //         width: 50,
    //         render: (dom, row) => (
    //             <>
    //                 <Tag color={row.isViolation == 1 ? "red" : "green"}>{row.isViolation == 1 ? "问题" : "正常"}</Tag>
    //             </>
    //         ),
    //     },
    //     {
    //         title: '标题',
    //         dataIndex: 'title',
    //         hideInSearch: true,
    //         ellipsis: true,
    //         // render: (dom, row) => (
    //         //   // <DetailMonitorVideo
    //         //   //   data={row}
    //         //   //   onRefurbish={() => {
    //         //   //     actionRef.current?.reload;
    //         //   //   }}
    //         //   // />
    //         //   <>
    //         //     {/* <DetailsMonitorArticle details={row} onRefurbish={actionRef.current?.reload} /> */}
    //         //     <div>
    //         //       <Tag color={row.isViolation==1?"red":"green"}>{row.isViolation==1?"问题":"正常"}</Tag>
    //         //       <span style={{ color: '#1677FF' }}>{row?.title}</span>
    //         //     </div>
    //         //   </>
    //         // ),
    //     },
    //     {
    //         title: '问题',
    //         key: 'violationCause',
    //         dataIndex: 'violationCause',
    //         render: (dom, row) => (
    //             <>
    //                 <Space wrap >
    //                     {row.violationCause?.map((item) => <Tag color='error'>{item}</Tag>)}
    //                 </Space>
    //             </>
    //         ),
    //     },
    //     {
    //         title: '媒体',
    //         key: 'mediaName',
    //         dataIndex: 'mediaName',
    //     },
    //     {
    //         title: '平台',
    //         key: 'platformName',
    //         dataIndex: 'platformName',
    //     },
    //     {
    //         title: '频道',
    //         key: 'channelName',
    //         dataIndex: 'channelName',
    //     },
    //     {
    //         title: '发布时间',
    //         dataIndex: 'releaseTime',
    //         key: 'releaseTime',
    //         width: '180px',
    //         align: 'center',
    //         search: false,
    //     },
    //     {
    //         title: '操作',
    //         dataIndex: 'articleUrl',
    //         key: 'articleUrl',
    //         width: '120px',
    //         align: 'center',
    //         search: false,
    //         render: (dom, entity, index, action, schema) => (
    //             <>
    //                 <Space>
    //                     <a href={entity?.sourceUrl} target="_blank">
    //                         查看原文
    //                     </a>
    //                     <a onClick={() => handleResolve(entity?.id)}>处理</a>
    //                 </Space>
    //             </>
    //         ),
    //     },
    // ];


    const loadCascadersSource = async () => {
        const response = await cascadersSource();
        if (response.code == 0) {
            setCascadersSourceDataState(response.data);
        }
    };

    const loadPageMonitorVideoRecordStatistics = async (queryParam: any) => {
        const response = await pageMonitorVideoRecordStatistics(queryParam);
        if (response.code == 0) {
            setPageMonitorVideoRecordStatisticsDataState(response.data);
        }
    };

    const getCascadersSource = () => {
        const channelIds = new Array();
        const levelIds = new Array();

        let channelId = formRef.current?.getFieldValue('channelId');
        let levelId = formRef.current?.getFieldValue('levelId');

        if (channelId == 'clean' || levelId == 'clean') {
            return;
        }

        if (channelId == 'all') {
            channelIds.push('8117112414994505', '8117112416043075');
        } else {
            channelIds.push(channelId);
        }

        if (levelId == 'all') {
            levelIds.push('2000', '3000');
        } else {
            levelIds.push(levelId);
        }

        let showCascadersData = new Array();

        cascadersSourceData.forEach((level) => {
            if (levelIds.includes(level.value)) {
                const showAreaData = new Array();

                const levelData = { ...level };

                level.children.forEach((area) => {
                    const sources = new Array();

                    let areaData = { ...area };

                    area.children
                        .filter((source) => channelIds.includes(source.channelId))
                        .forEach((source) => {
                            sources.push({
                                label: `${source.label} (${source.channelName})`,
                                value: source.value,
                                channelId: source.channelId,
                                channelName: source.channelName,
                            });
                        });

                    if (sources.length > 0) {
                        areaData.children = sources;
                        showAreaData.push(areaData);
                    }
                });

                if (showAreaData.length > 0) {
                    levelData.children = showAreaData;
                    showCascadersData.push(levelData);
                }
            }
        });

        setOptionsCascadersSourceDataState(showCascadersData);
    };

    const getCascadersMedia = async () => {
        const res = await mediaList()
        if (res.code === 0) {
            setOptionsCascadersSourceDataState(res.data);
        }
    }

    const getCascadersPlatform = async () => {
        const res = await platformList()
        if (res.code === 0) {
            const list = new Array()
            list.push([{ label: '全部', value: "" }, ...res.data])
            console.log(list);
            setOptionsPlatformData(...list)
        }
    }

    useEffect(() => {
        loadCascadersSource();
        loadPageMonitorVideoRecordStatistics({});
        // getCascadersMedia()
        // getCascadersPlatform()
    }, []);


    return (
        <PageContainer
            style={{ background: '#FFF' }}
            header={{
                breadcrumb: {
                    items: [],
                },
                style: {
                    paddingBlockEnd: 0,
                },
            }}
            content={
                <RcResizeObserver
                    key="resize-observer"
                >
                    {/* <QueryFilter
                        submitter={false}
                        span={24}
                        labelWidth="auto"
                        split
                        formRef={formRef}
                        initialValues={{
                            channelId: '', //渠道=全部
                            platformId: '',
                            levelId: 'all', //媒体=全部
                            sourceIds: [], //媒体选择框=空
                            // time: '最近90天',
                            // releaseTimes: [moment().subtract(89, 'days'), moment()],
                        }}
                        onFinish={async (value) => {
                            if (
                                value.sourceIds.length == 0 &&
                                value.channelId != 'all' &&
                                value.channelId != 'clean'
                            ) {
                                value.sourceChannelIds = [value.channelId];
                            } else {
                                value.sourceChannelIds = [];
                            }

                            if (
                                value.sourceIds.length == 0 &&
                                value.levelId != 'all' &&
                                value.levelId != 'clean'
                            ) {
                                value.sourceLevelIds = [value.levelId];
                            } else {
                                value.sourceLevelIds = [];
                            }

                            if (value.sourceIds != undefined && value.sourceIds.length !== 0) {
                                let sourceIds = new Array();

                                value.sourceIds.forEach((item: any[]) => {
                                    const option = item[item.length - 1];
                                    sourceIds.push(option);
                                });
                                value.sourceIds = sourceIds;
                            }
                            value.startTime = value.releaseTimes[0]
                            value.endTime = value.releaseTimes[1]
                            console.log(value);
                            setQueryParamState({ ...queryParam, ...value });
                            // loadPageMonitorVideoRecordStatistics({ ...queryParam, ...value });
                            actionRef.current?.reloadAndRest()
                        }}
                    >
                        <ProForm.Group title="平台">
                            <ProFormRadio.Group
                                name="platformId"
                                radioType="button"
                                options={optionsPlatformData}
                                fieldProps={{
                                    // options: {},
                                    onChange: () => {
                                        formRef.current?.setFieldValue('sourceIds', []);

                                        let levelId = formRef.current?.getFieldValue('levelId');

                                        if (levelId == 'clean') {
                                            formRef.current?.setFieldValue('levelId', 'all');
                                        }

                                        // getCascadersSource();
                                        formRef.current?.submit();
                                    },
                                }}
                            />
                            <ProFormCascader
                                name="sourceIds"
                                placeholder="选择媒体"
                                fieldProps={{
                                    options: optionsCascadersSourceData,
                                    style: { width: 400 },
                                    multiple: true,
                                    removeIcon: true,
                                    allowClear: true,
                                    showSearch: true,
                                    maxTagCount: 'responsive',
                                    showCheckedStrategy: Cascader.SHOW_CHILD,
                                    onClear() {
                                        // formRef.current?.setFieldValue('channelId', 'clean');
                                        // formRef.current?.setFieldValue('levelId', 'clean');
                                        // getCascadersSource();
                                        formRef.current?.submit();
                                    },
                                    onChange(value, selectOptions) {
                                        // let channelId = formRef.current?.getFieldValue('channelId');
                                        // let levelId = formRef.current?.getFieldValue('levelId');

                                        // if (channelId == 'clean' && levelId == 'clean') {
                                        //     formRef.current?.setFieldValue('channelId', 'all');
                                        //     formRef.current?.setFieldValue('levelId', 'all');
                                        // }

                                        // if (value.length > 0) {
                                        //     formRef.current?.setFieldValue('channelId', 'clean');
                                        //     formRef.current?.setFieldValue('levelId', 'clean');
                                        // }

                                        formRef.current?.submit();
                                    },
                                }}
                            />
                        </ProForm.Group>
                        <ProForm.Group title="发布时间">
                            <ProFormRadio.Group
                                name="time"
                                radioType="button"
                                options={[
                                    { label: '今天', value: '今天' },
                                    { label: '本月', value: '本月' },
                                    { label: '上月', value: '上月' },
                                    { label: '最近7天', value: '最近7天' },
                                    { label: '最近60天', value: '最近60天' },
                                    { label: '最近90天', value: '最近90天' },
                                ]}
                                fieldProps={{
                                    onChange: () => {
                                        const time = formRef.current?.getFieldValue('time');
                                        if (time === '今天') {
                                            formRef.current?.setFieldValue('releaseTimes', [moment(), moment()]);
                                        } else if (time === '本月') {
                                            formRef.current?.setFieldValue('releaseTimes', [
                                                moment().startOf('month'),
                                                moment().endOf('month'),
                                            ]);
                                        } else if (time === '上月') {
                                            formRef.current?.setFieldValue('releaseTimes', [
                                                moment().startOf('month').subtract(1, 'months'),
                                                moment().endOf('month').subtract(1, 'months'),
                                            ]);
                                        } else if (time === '最近7天') {
                                            formRef.current?.setFieldValue('releaseTimes', [
                                                moment().subtract(6, 'days'),
                                                moment(),
                                            ]);
                                        } else if (time === '最近60天') {
                                            formRef.current?.setFieldValue('releaseTimes', [
                                                moment().subtract(59, 'days'),
                                                moment(),
                                            ]);
                                        } else if (time === '最近90天') {
                                            formRef.current?.setFieldValue('releaseTimes', [
                                                moment().subtract(89, 'days'),
                                                moment(),
                                            ]);
                                        }
                                        formRef.current?.submit();
                                    },
                                }}
                            />
                            <ProFormDateRangePicker
                                name="releaseTimes"
                                fieldProps={{
                                    onChange(dates, dateStrings) {
                                        formRef.current?.setFieldValue('time', ' ');
                                        formRef.current?.submit();
                                    },
                                }}
                            />
                        </ProForm.Group>
                    </QueryFilter> */}
                    <QueryFilter
                        submitter={false}
                        span={24}
                        labelWidth="auto"
                        split
                        formRef={formRef}
                        initialValues={{
                            channelId: 'all', //渠道=全部
                            levelId: 'all', //媒体=全部
                            sourceIds: [], //媒体选择框=空
                            // time: '最近90天',
                            // releaseTimes: [moment().subtract(89, 'days'), moment()],
                        }}
                        onFinish={async (value) => {

                            console.log(value.releaseTimes);
                            
                            if (
                                value.sourceIds.length == 0 &&
                                value.channelId != 'all' &&
                                value.channelId != 'clean'
                            ) {
                                value.sourceChannelIds = [value.channelId];
                            } else {
                                value.sourceChannelIds = [];
                            }

                            if (
                                value.sourceIds.length == 0 &&
                                value.levelId != 'all' &&
                                value.levelId != 'clean'
                            ) {
                                value.sourceLevelIds = [value.levelId];
                            } else {
                                value.sourceLevelIds = [];
                            }

                            if (value.sourceIds != undefined && value.sourceIds.length !== 0) {
                                let sourceIds = new Array();

                                value.sourceIds.forEach((item: any[]) => {
                                    const option = item[item.length - 1];
                                    sourceIds.push(option);
                                });
                                value.sourceIds = sourceIds;
                            }

                            setQueryParamState({ ...queryParam, ...value });
                            loadPageMonitorVideoRecordStatistics({ ...queryParam, ...value });
                            actionRef.current?.reloadAndRest();
                        }}
                    >
                        <ProForm.Group title="媒体">
                            <ProFormRadio.Group
                                name="channelId"
                                radioType="button"
                                options={[
                                    { label: '全部', value: 'all' },
                                    {
                                        label: '抖音',
                                        value: '8117112414994505',
                                    },
                                    { label: '快手', value: '8117112416043075' },
                                ]}
                                fieldProps={{
                                    onChange: () => {
                                        formRef.current?.setFieldValue('sourceIds', []);

                                        let levelId = formRef.current?.getFieldValue('levelId');

                                        if (levelId == 'clean') {
                                            formRef.current?.setFieldValue('levelId', 'all');
                                        }

                                        getCascadersSource();
                                        formRef.current?.submit();
                                    },
                                }}
                            />
                            <ProFormRadio.Group
                                name="levelId"
                                radioType="button"
                                options={[
                                    { label: '全部', value: 'all' },
                                    { label: '市属媒体', value: '2000' },
                                    { label: '区县媒体', value: '3000' },
                                ]}
                                fieldProps={{
                                    onChange: () => {
                                        formRef.current?.setFieldValue('sourceIds', []);

                                        let channelId = formRef.current?.getFieldValue('channelId');

                                        if (channelId == 'clean') {
                                            formRef.current?.setFieldValue('channelId', 'all');
                                        }

                                        getCascadersSource();
                                        formRef.current?.submit();
                                    },
                                }}
                            />
                            <ProFormCascader
                                name="sourceIds"
                                placeholder="选择媒体"
                                fieldProps={{
                                    options: optionsCascadersSourceData,
                                    style: {
                                        width: 300,
                                    },
                                    multiple: true,
                                    removeIcon: true,
                                    allowClear: true,
                                    showSearch: true,
                                    maxTagCount: 'responsive',
                                    showCheckedStrategy: Cascader.SHOW_CHILD,
                                    onClear() {
                                        formRef.current?.setFieldValue('channelId', 'clean');
                                        formRef.current?.setFieldValue('levelId', 'clean');
                                        getCascadersSource();
                                        formRef.current?.submit();
                                    },
                                    onChange(value, selectOptions) {
                                        let channelId = formRef.current?.getFieldValue('channelId');
                                        let levelId = formRef.current?.getFieldValue('levelId');

                                        if (channelId == 'clean' && levelId == 'clean') {
                                            formRef.current?.setFieldValue('channelId', 'all');
                                            formRef.current?.setFieldValue('levelId', 'all');
                                        }

                                        if (value.length > 0) {
                                            formRef.current?.setFieldValue('channelId', 'clean');
                                            formRef.current?.setFieldValue('levelId', 'clean');
                                        }

                                        formRef.current?.submit();
                                    },
                                }}
                            />
                        </ProForm.Group>
                        <ProForm.Group title="发布时间">
                            <ProFormRadio.Group
                                name="time"
                                radioType="button"
                                options={[
                                    { label: '今天', value: '今天' },
                                    { label: '本月', value: '本月' },
                                    { label: '上月', value: '上月' },
                                    { label: '最近7天', value: '最近7天' },
                                    { label: '最近60天', value: '最近60天' },
                                    { label: '最近90天', value: '最近90天' },
                                ]}
                                fieldProps={{
                                    onChange: () => {
                                        const time = formRef.current?.getFieldValue('time');
                                        if (time === '今天') {
                                            formRef.current?.setFieldValue('releaseTimes', [moment(), moment()]);
                                        } else if (time === '本月') {
                                            formRef.current?.setFieldValue('releaseTimes', [
                                                moment().startOf('month'),
                                                moment().endOf('month'),
                                            ]);
                                        } else if (time === '上月') {
                                            formRef.current?.setFieldValue('releaseTimes', [
                                                moment().startOf('month').subtract(1, 'months'),
                                                moment().endOf('month').subtract(1, 'months'),
                                            ]);
                                        } else if (time === '最近7天') {
                                            formRef.current?.setFieldValue('releaseTimes', [
                                                moment().subtract(6, 'days'),
                                                moment(),
                                            ]);
                                        } else if (time === '最近60天') {
                                            formRef.current?.setFieldValue('releaseTimes', [
                                                moment().subtract(59, 'days'),
                                                moment(),
                                            ]);
                                        } else if (time === '最近90天') {
                                            formRef.current?.setFieldValue('releaseTimes', [
                                                moment().subtract(89, 'days'),
                                                moment(),
                                            ]);
                                        }
                                        formRef.current?.submit();
                                    },
                                }}
                            />
                            <ProFormDateRangePicker
                                name="releaseTimes"
                                fieldProps={{
                                    onChange(dates, dateStrings) {
                                        formRef.current?.setFieldValue('time', ' ');
                                        formRef.current?.submit();
                                    },
                                    
                                }}
                            />
                        </ProForm.Group>
                    </QueryFilter>
                </RcResizeObserver>
            }
        >
            <ProTable<MonitorVideoData.VideoRecordPage>
                cardBordered
                actionRef={actionRef}
                columns={columns}
                request={async (params = {}) => {
                    const response = await pageMonitorVideo({
                        isViolation: 1,
                        ...params,
                        ...queryParam
                    });

                    return Promise.resolve({
                        data: response.data.data,
                        total: response.data.total,
                        success: response.code === 0,
                    });
                }}
                search={false}
                rowKey="key"
                options={false}
                toolbar={{
                    search: {
                        placeholder: '请输入文章标题搜索',
                        allowClear: true,
                        onSearch: (value: string) => {
                            setQueryParamState({ ...queryParam, title: value });
                            formRef.current?.submit();
                        },
                    },
                    actions: [
                        <AddMonitorLinkage onClose={() => { actionRef.current?.reload() }} />,
                    ],
                }}
            />
        </PageContainer>
    );
};

export default PageContainerMonitorLinkage;
